package com.glodon.paas.account.dao.mysql;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;

import com.glodon.paas.account.dao.ClientRegistryDao;
import com.glodon.paas.account.dao.ConsumerDao;
import com.glodon.paas.account.dao.domain.ConsumerEntity;
import com.glodon.paas.account.service.util.PaasRegisteredClientImpl;
 
public class ConsumerDaoMysqlImpl implements ConsumerDao{
/*	@Autowired
	private ConsumerEntityMapper consumerEntityMapper; 
	
	@Override
	public String insert(ConsumerEntity entity) {
		consumerEntityMapper.insertSelective(entity);
		return entity.getId();
	}

	@Override
	public ConsumerEntity get(String id) {
		return consumerEntityMapper.selectByPrimaryKey(id);
	}

	@Override
	public int delete(String id) {
		return consumerEntityMapper.deleteByPrimaryKey(id);
	}

	@Override
	public ConsumerEntity getConsumerByKey(String consumerkey) {
		return consumerEntityMapper.selectByConsumerKey(consumerkey);
	}*/
	
	@Autowired
	private ClientRegistryDao clientRegistryDao; ;
	
	@Override
	public String insert(ConsumerEntity entity) {		
		clientRegistryDao.addClientDetails(convert(entity));
		return entity.getId();
	}

	@Override
	public ConsumerEntity get(String id) {
		List<ClientDetails> clinetList = clientRegistryDao.listClientDetails();
		for(ClientDetails c : clinetList){
			if(c.getClientId().equals(id)){
				return convert(c);
			}
		}
		return null;
	}

	@Override
	public int delete(String id) {
		clientRegistryDao.removeClientDetails(id);
		 return 1;
	}

	@Override
	public ConsumerEntity getConsumerByKey(String consumerkey) {		
		return convert(clientRegistryDao.loadClientByClientId(consumerkey));
	}

	private ConsumerEntity convert(ClientDetails client){
		if(client != null && client instanceof PaasRegisteredClientImpl){
			ConsumerEntity entity = new ConsumerEntity(); 			
			entity.setCallbackURL(client.getRegisteredRedirectUri().iterator().next());
			entity.setConsumerkey(client.getClientId());
			entity.setConsumerSecrect(client.getClientSecret());
			entity.setDescription(((PaasRegisteredClientImpl)client).getDescription());
			return entity;
		}
		return null;
	}
	private ClientDetails convert(ConsumerEntity entity){
		if(entity != null){
			PaasRegisteredClientImpl client = new PaasRegisteredClientImpl();
			client.setClientId(entity.getConsumerkey());
			client.setClientSecret(entity.getConsumerSecrect());
			client.setDescription(entity.getDescription());
			Set<String> set = new HashSet<String>();
			set.add(entity.getCallbackURL());
			client.setRegisteredRedirectUri(set);
			return client;
		}
		return null;
	}
}

